package com.zimmur.service.impl.zone;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Throwables;
import com.zimmur.common.AppModuleEnum;
import com.zimmur.common.ConstData;
import com.zimmur.common.EnumPointRule;
import com.zimmur.dao.zone.ITopicCollectDao;
import com.zimmur.dao.zone.ITopicCommentDao;
import com.zimmur.dao.zone.ITopicDao;
import com.zimmur.dao.zone.ITopicGoodsDao;
import com.zimmur.dao.zone.ITopicPictureDao;
import com.zimmur.dao.zone.ITopicRecommandDao;
import com.zimmur.model.account.AccountInfo;
import com.zimmur.model.account.GoodsUser;
import com.zimmur.model.account.UserjeLog;
import com.zimmur.model.base.AdBanner;
import com.zimmur.model.goods.Goods;
import com.zimmur.model.goods.GoodsImage;
import com.zimmur.model.zone.SharedProperty;
import com.zimmur.model.zone.Topic;
import com.zimmur.model.zone.TopicComment;
import com.zimmur.model.zone.TopicConcern;
import com.zimmur.model.zone.TopicExample;
import com.zimmur.model.zone.TopicGoods;
import com.zimmur.model.zone.TopicNotice;
import com.zimmur.model.zone.TopicPicture;
import com.zimmur.model.zone.TopicRecommand;
import com.zimmur.service.IAccountInfoService;
import com.zimmur.service.IUserService;
import com.zimmur.service.RedisCacheUtil;
import com.zimmur.service.account.IPointLogService;
import com.zimmur.service.base.IAdBannerService;
import com.zimmur.service.fdfs.IStorageFilesService;
import com.zimmur.service.goods.IGoodsImageService;
import com.zimmur.service.goods.IGoodsService;
import com.zimmur.service.impl.account.UserjeLogServiceImpl;
import com.zimmur.service.zone.ITopicCollectService;
import com.zimmur.service.zone.ITopicCommentService;
import com.zimmur.service.zone.ITopicConcernService;
import com.zimmur.service.zone.ITopicMessageRecommandService;
import com.zimmur.service.zone.ITopicNoticeService;
import com.zimmur.service.zone.ITopicRecommandService;
import com.zimmur.service.zone.ITopicService;
import com.zimmur.solr.service.ISolrTopicService;
import com.zimmur.tools.DateUtils;
import com.zimmur.tools.HtmlToTextUtil;
import com.zimmur.tools.PageUtil;
import com.zimmur.tools.PageUtil_TopicCollect;
  
  
@Service("topicService")  
public class TopicServiceImpl implements ITopicService {  
    private static Logger log=LoggerFactory.getLogger(TopicServiceImpl.class);
    @Resource  
    private ITopicDao topicDao;
    @Resource  
    private ITopicCommentDao topicCommentDao;
    @Resource  
    private ITopicCollectDao topicCollectDao;
    @Resource  
    private ITopicGoodsDao topicGoodsDao;
    @Resource  
    private ITopicPictureDao topicPictureDao;
    @Resource  
    private ITopicNoticeService topicNoticeService;
    @Resource  
    private ITopicConcernService  topicConcernService;
    @Resource  
    private ITopicCollectService  topicCollectService;
    @Resource  
    private ITopicCommentService  topicCommentService;
    @Resource  
    private ITopicRecommandService  topicRecommandService;
    @Resource
    private ITopicMessageRecommandService topicMessageRecommandService;
    @Resource  
    private IGoodsService  goodsService;
    @Resource  
    private IGoodsImageService  goodsImageService;

	@Resource
    private IPointLogService pointService;
    @Resource  
    private IUserService  userService;
    @Resource
    private IAccountInfoService accountInfoService;
    @Resource
	private UserjeLogServiceImpl userjeLogService;
	@Resource
	private RedisCacheUtil<Topic> stringRedisDao;
	@Resource
	private IStorageFilesService storageFilesService;
	@Resource
	private IAdBannerService abBannerService;
	@Resource 
	private ISolrTopicService solrTopicService;
	
	private final String redis_key ="popolook_topic";
    
	private static Object syncLock = new Object();
	private static Object syncLockList = new Object();
    @Override
	public TopicExample topicIndex(long createUserId) {
		TopicExample topicExample=new TopicExample();
		try {
			/*//社区公告
			List<TopicNotice> topicNoticeList = topicNoticeService.selectTopicNoticeListLimit(5);
			if(topicNoticeList !=null && topicNoticeList.size() > 0){
				topicExample.setTopicNoticeList(topicNoticeList);
			}*/
			//广告
			List<AdBanner> adBannerList = abBannerService.selectAdList(Integer.parseInt(AppModuleEnum.Zone.getModuleId()));
			
	    	//推荐话题红人
	    	List<GoodsUser> hotUserList=topicRecommandService.selectTopicRecommandList3(ConstData.TOPIC_TYPE_HOT, createUserId);
	    	//推荐话题达人
	    	List<GoodsUser> drUserList=topicRecommandService.selectTopicRecommandList3(ConstData.TOPIC_TYPE_TALENT, createUserId);
	    	PageUtil<Topic> cyTopicList=topicPage(createUserId, 1,ConstData.TOPIC_TYPE_HOT);
	    	PageUtil<Topic> drTopicList=topicPage(createUserId, 1,ConstData.TOPIC_TYPE_TALENT);
	    	PageUtil<Topic> qzTopicList=topicPage(createUserId, 1,ConstData.TOPIC_TYPE_HELP);
	    	
	    	topicExample.setAdBannerList(adBannerList);
	    	topicExample.setCyTopicList(cyTopicList);
	    	topicExample.setDrTopicList(drTopicList);
	    	topicExample.setQzTopicList(qzTopicList);
	    	topicExample.setHotUserList(hotUserList);
	    	topicExample.setDarenUserList(drUserList);
	    	
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return topicExample;
	}
	@Override
	public PageUtil<Topic> topicPage(long createUser, Integer pageNow,short topicType) {
		if(pageNow == 0){
			pageNow=1;
		}
		PageUtil<Topic> page = new PageUtil<>();
		String TopicPage_RedisKey = redis_key+"_"+createUser+"_"+ pageNow+"_"+topicType+"_topicPage_1";
		String TopicPage_Count_Key = redis_key+"_"+topicType+"_topicPage_count_1";
		List<Topic> topicList = new ArrayList<>();
		//获取 最大值
		Integer totalRecord = 0;
		boolean countExist=false;
		try {
			countExist=stringRedisDao.exists(TopicPage_Count_Key);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if(countExist){
			totalRecord = Integer.parseInt(stringRedisDao.getCacheString(TopicPage_Count_Key));
		}else{
			synchronized (syncLock) {
				try {
					countExist=stringRedisDao.exists(TopicPage_Count_Key);
				} catch (Exception e) {
					log.error(e.getMessage());
				}
				if(countExist){
					totalRecord = Integer.parseInt(stringRedisDao.getCacheString(TopicPage_Count_Key));
				}else{
					log.info("search for DB");
					SharedProperty sp=new SharedProperty();
			    	sp.setTopicType(topicType);
			    	//统计话题总数
			    	totalRecord =topicDao.countTopicByTopicType(sp);
		    		try {
		    			log.info("save to redis");
		    			stringRedisDao.setCacheString(TopicPage_Count_Key, String.valueOf(totalRecord));
		    			stringRedisDao.setTimeout(TopicPage_Count_Key, ConstData.REDIS_KEY_TIMEOUT);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
				}
			}
		}
		
		boolean listExist=false;
		try {
			listExist=stringRedisDao.exists(TopicPage_RedisKey);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if(listExist){
			topicList = stringRedisDao.getCacheList(TopicPage_RedisKey);
		}else{
			synchronized (syncLockList) {
				try {
					listExist=stringRedisDao.exists(TopicPage_RedisKey);
				} catch (Exception e) {
					log.error(e.getMessage());
				}
				if(listExist){
					topicList = stringRedisDao.getCacheList(TopicPage_RedisKey);
				}else{
					SharedProperty sp=new SharedProperty();
					sp.setCreateUser(createUser);
			    	sp.setPageNow(pageNow);
			    	sp.setTopicType(topicType);
			    	//查询话题
			    	topicList=topicDao.selectTopicByTopicType(sp);
					if(topicList!=null && topicList.size()>0){
						//int type=topicType;
						for(Topic topicItem : topicList){
							//清除content里的html代码
							topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
				    		//话题图片
					    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
					    	topicItem.setTopicPictures(topicPictureList);
						}
					}
					if(topicList!=null && topicList.size()>0){
						try {
							stringRedisDao.setCacheList(TopicPage_RedisKey, topicList);
							stringRedisDao.setTimeout(TopicPage_RedisKey, ConstData.REDIS_KEY_TIMEOUT);
						} catch (Exception e) {
							log.error(e.getMessage());
						}
					}
				}
			}		
		}
		if(topicList!=null && topicList.size()>0){
			
			try {
				for(Topic topicItem : topicList){
					GoodsUser user =userService.selectTopicIsConcern(createUser,topicItem.getCreateUser(),null);
					if(user !=null){
						topicItem.setUser(user);
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
			page.setItemList(topicList);
		}
		page.setPageNo(pageNow);
		page.setTotalRecord(totalRecord);
		return page;
	}
	
    
    
	@Override
	public int insertTopicAndStar(Topic topic) {
		 Integer resut=topicDao.insertTopicAndStar(topic);
		 pointService.mainPointLog(topic.getCreateUser(), "话题发布", EnumPointRule.XK_ADD_TOPIC, 0);
		 return resut;
		
	}

	@Override
	public int insertTopicAndKnow(Topic topic) {
		Integer resut=topicDao.insertTopicAndKnow(topic);
		pointService.mainPointLog(topic.getCreateUser(), "话题悬赏发布", EnumPointRule.ZK_ADD_TOPIC, 0);
		return resut;
	}
	
	@Override
	public int addTopic(Topic topic,String categoryCode) {
		Integer resut=0;
		if("xk".equals(categoryCode)){
	    	//星客存储，推荐商品    //
	    	//
	    	resut=topicDao.insertTopicAndStar(topic);
	    }
	    if("zk".equals(categoryCode)){
	    	
	        resut= topicDao.insertTopicAndKnow(topic);
	    } 
		return resut;
	}
	
	@Override
	public List<Topic> userIdTopicListPage(long createUser, Integer pageNow) {
		List<Topic> topicLists=new ArrayList<>();
//		PageUtil<Topic> page=new PageUtil<>();
		try {
//			Integer totalRecord= topicDao.selectUserIdCounttopic(createUser);			
//			page.setTotalRecord(totalRecord);
			if(pageNow == 0){
				pageNow=1;
			}
			SharedProperty sp=new SharedProperty();
	    	sp.setCreateUser(createUser);
	    	sp.setPageNow(pageNow);
	    	List<Topic> topicListsS=topicDao.pageTopicList(sp);
	    	for(Topic topicItem : topicListsS){
	    		//话题图片
		    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
		    	topicItem.setTopicPictures(topicPictureList);
				//根据设计师ID查询是否当前用户以关注
				//int topicType=topicItem.getTopicType()==null?3:topicItem.getTopicType();
				GoodsUser user =userService.selectTopicIsConcern(createUser,topicItem.getCreateUser(),null);
	    		if(user != null){
	    			topicItem.setUser(user);
	    		}
	    		topicLists.add(topicItem);
	    	}
//	    	page.setItemList(topicLists);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return topicLists;
	}
	
	@Override
	public com.zimmur.restful.model.Topic selectByTopicId(long topicId, long userId) {
		com.zimmur.restful.model.Topic topic = new com.zimmur.restful.model.Topic();
		try {
			SharedProperty sp=new SharedProperty();
	    	sp.setCreateUser(userId);
	    	sp.setTopicId(topicId);
	    	sp.setPageNow(1);
	    	
	    	topic= topicDao.selectByTopicIdToView(topicId,userId);
	    	if(topic != null){
	    		//话题图片
		    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topic.getTopicId());
		    	if(!topicPictureList.isEmpty()){
		    		List<com.zimmur.restful.model.TopicPicture> topicPictures = new ArrayList<>();
		    		for (TopicPicture topicPicture : topicPictureList) {
		    			com.zimmur.restful.model.TopicPicture picture = new com.zimmur.restful.model.TopicPicture();
		    			picture.setPictureId(topicPicture.getPictureId());
		    			picture.setTopicId(topicPicture.getTopicId());
		    			picture.setImageUrl("");
		    			picture.setMemo(topicPicture.getMemo());
		    			picture.setCreateDate(topicPicture.getCreateDate());
		    			picture.setGoodsId(topicPicture.getGoodsId());
		    			picture.setTypeFlag(topicPicture.getTypeFlag());
		    			if(topicPicture.getImageUrl().equals("")){
		    				picture.setFileInfo(null);
		    			}else{
		    				picture.setFileInfo(storageFilesService.selectByFileId(Long.parseLong(topicPicture.getImageUrl())));
		    			}
		    			
		    			topicPictures.add(picture);
					}
		    		topic.setTopicPictures(topicPictures);
		    		topicPictureList=null;
		    	}
		    	
				GoodsUser user =userService.selectGoodsIsConcern(userId,topic.getCreateUser());	
				topic.setUser(user);
				
	    	}
	    	//推荐商品
			TopicGoods topicGoods=new TopicGoods();
			topicGoods.setTopicId(topicId);
			List<TopicGoods> topicGoodsList= topicGoodsDao.selectTopicGoodsList(topicGoods);
			if(!topicGoodsList.isEmpty()){
				List<Long> goodsIds=new ArrayList<>();
				for(TopicGoods topicGoodsItem :topicGoodsList){
					goodsIds.add(topicGoodsItem.getGoodsId());
				}
				List<Goods> goodsList =goodsService.selectByGoodsIdsAndTypeFlag(goodsIds,1);
				if(!goodsList.isEmpty() && goodsList.size() > 0){
					topic.setGoodsList(goodsList);
				}
				
			}
			//话题评论 
	    	List<TopicComment> topicCommentList = topicCommentService.pageCommentList(topicId,userId, 0);
	    	if(!topicCommentList.isEmpty()){
	    		topic.setTopicComments(topicCommentList);
	    	}
	    	if(topic != null){
				/*浏览数增加*/
		        Topic topics =new Topic();
		        Integer browserNum= topic.getBrowserNum()+1;
		        topics.setBrowserNum(browserNum);
		        topics.setTopicId(topicId);
		        topicDao.updateStopicBrowserNum(topics);	
	    	}
		}catch (Exception e) {
			log.error(e.getMessage());
		}
		return topic;
	}
	
	
	
	@Override
	public com.zimmur.restful.model.Topic selectByTopicIdV120(long topicId,long userId) {
		com.zimmur.restful.model.Topic topic = new com.zimmur.restful.model.Topic();
		try {
			SharedProperty sp=new SharedProperty();
	    	sp.setCreateUser(userId);
	    	sp.setTopicId(topicId);
	    	sp.setPageNow(1);
	    	
	    	topic= topicDao.selectByTopicIdToView(topicId,userId);
	    	//判断为非html内容时, 处理tab及enter标记为html空格(&nbsp;)和换行(<br/>)标记符
	    	String content=topic.getContent();
	    	/*if(content!=null &&!content.matches("<(S*?)[^>]*>.*?|<.*? /> ")){
	    		content=content.replace("\r\n", "<br/>").replace(" ", "&nbsp;");
		    	topic.setContent(content);
	    	}*/
	    	if(content!=null ){
				Pattern r = Pattern.compile("<(S*?)[^>]*>.*?|<.*? />");
			    Matcher m = r.matcher(content);
			    if(!m.find()){
			    	content=content.replace("\r\n", "<br/>").replace(" ", "&nbsp;").replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
			    	topic.setContent(content);
			    }
			}
	    	if(topic != null){
	    		//话题图片
		    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topic.getTopicId());
		    	if(!topicPictureList.isEmpty()){
		    		List<com.zimmur.restful.model.TopicPicture> topicPictures = new ArrayList<>();
		    		for (TopicPicture topicPicture : topicPictureList) {
		    			com.zimmur.restful.model.TopicPicture picture = new com.zimmur.restful.model.TopicPicture();
		    			picture.setPictureId(topicPicture.getPictureId());
		    			picture.setTopicId(topicPicture.getTopicId());
		    			picture.setImageUrl("");
		    			
		    			picture.setCreateDate(topicPicture.getCreateDate());
		    			picture.setGoodsId(topicPicture.getGoodsId());
		    			picture.setTypeFlag(topicPicture.getTypeFlag());
		    			if(topicPicture.getImageUrl().equals("")){
		    				picture.setFileInfo(null);
		    			}else{
		    				picture.setFileInfo(storageFilesService.selectByFileId(Long.parseLong(topicPicture.getImageUrl())));
		    			}
		    			//话题商品
		    			if(topicPicture.getGoodsId()!=0){
			    			Goods goods=goodsService.selectByGoodsId(topicPicture.getGoodsId());
			    			if(goods!=null){
			    				String title=goods.getTitle();
			    				String goodsContent=goods.getSmallDesc();
			    				if(title.length()>14){
			    					title=title.substring(0, 14)+"...";
			    				}
			    				if(goodsContent.length()>14){
			    					goodsContent=goodsContent.substring(0, 14)+"...";
			    				}
			    				picture.setGoods("title",title);
			    				picture.setGoods("price", goods.getPrice());
			    				picture.setGoods("content", goodsContent);
			    			}else{
			    				picture.setGoodsId(0);
			    			}
			    		}
		    			
		    			String picStr=topicPicture.getMemo();
		    			if(picStr!=null){
		    				Pattern r = Pattern.compile("<(S*?)[^>]*>.*?|<.*? />");
		    			    Matcher m = r.matcher(picStr);
		    			    if(!m.find()){
		    			    	picStr=picStr.replace("\r\n", "<br/>").replace(" ", "&nbsp;").replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
			    				picture.setMemo(picStr);
		    			    }else{
		    			    	picture.setMemo(picStr);
		    			    }
		    			}
		    		/*	if(picStr!=null &&!picStr.matches("<(S*?)[^>]*>.*?|<.*? />")){
		    				picStr=picStr.replace("\r\n", "<br/>").replace(" ", "&nbsp;");
		    				picture.setMemo(picStr);
		    	    	}else{
		    	    		picture.setMemo(topicPicture.getMemo());
		    	    	}*/
		    			
		    			
		    			topicPictures.add(picture);
					}
		    		topic.setTopicPictures(topicPictures);
		    		topicPictureList=null;
		    	}

		    	//根据设计师ID查询是否当前用户以关注
				int topicType=topic.getTopicType()==null?3:topic.getTopicType();
				GoodsUser user =userService.selectTopicIsConcern(userId,topic.getCreateUser(),null);
				topic.setUser(user);
				
	    	}
	    	//推荐商品
			TopicGoods topicGoods=new TopicGoods();
			topicGoods.setTopicId(topicId);
			List<TopicGoods> topicGoodsList= topicGoodsDao.selectTopicGoodsList(topicGoods);
			if(!topicGoodsList.isEmpty()){
				List<Long> goodsIds=new ArrayList<>();
				for(TopicGoods topicGoodsItem :topicGoodsList){
					goodsIds.add(topicGoodsItem.getGoodsId());
				}
				List<Goods> goodsList =goodsService.selectByGoodsIdsAndTypeFlag(goodsIds,1);
				if(!goodsList.isEmpty() && goodsList.size() > 0){
					topic.setGoodsList(goodsList);
				}
				
			}
			//话题评论 
	    	List<TopicComment> topicCommentList = topicCommentService.pageCommentList(topicId,userId, 0);
	    	if(!topicCommentList.isEmpty()){
	    		topic.setTopicComments(topicCommentList);
	    	}
	    	if(topic != null){
				/*浏览数增加*/
		        Topic topics =new Topic();
		        Integer browserNum= topic.getBrowserNum()+1;
		        topics.setBrowserNum(browserNum);
		        topics.setTopicId(topicId);
		        topicDao.updateStopicBrowserNum(topics);	
	    	}
		}catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return topic;
	}

	@Override
	public int updateStopicBrowserNum(Topic topic) {
		int flag=0;
		try {
			flag = topicDao.updateStopicBrowserNum(topic);
			saveTopicIdToRedis(topic.getTopicId());
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return flag;
	}

	@Override
	public int updateStopicShareNum(long topicId,long createUser) {
		Integer resut=0;
		try {
			Topic topic= topicDao.selectByIdstopic(topicId);
			if(topic != null){
				//转发
				Topic topics =new Topic();
				Integer shareNum=topic.getShareNum()+1;
				topics.setShareNum(shareNum);
				topics.setTopicId(topicId);
				resut=topicDao.updateStopicShareNum(topics);
				
				topicSharePoint(topic.getCreateUser(),createUser);
				saveTopicIdToRedis(topicId);
				return resut;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return resut;
	}
    /**
     * 用户话题被分享,积分增加规则
     * @param userId
     */
	private void topicSharePoint(long toUserId,long userId){
		if(userId>0){
			GoodsUser fromUser = userService.selectByUserId(userId);
			if(fromUser.getCategoryCode().equals("zk")){
				pointService.mainPointLog(userId, "话题分享", EnumPointRule.ZK_SHARE, 0);
			}
			if(fromUser.getCategoryCode().equals("xk")){
				pointService.mainPointLog(toUserId, "话题分享", EnumPointRule.XK_SHARE, 0);
			}
			GoodsUser toUser=userService.selectByUserId(toUserId);
			if(toUser.getCategoryCode().equals("xk")){
				pointService.mainPointLog(toUserId, "话题被转发", EnumPointRule.XK_SHARE_TO, 0);
			}
		}
	}
	
	@Override
	public PageUtil_TopicCollect userIdTopicPageList(long createUser,Long userId,Integer pageNow,String key) {
		PageUtil_TopicCollect page=new PageUtil_TopicCollect();
		
		String Redis_Key=redis_key+"_"+userId+"_"+pageNow+"_"+key+"_userIdTopicPageList";
		String Redis_Key_Count=redis_key+"_"+userId+"_"+key+"_userIdTopicPageList_count";
		
		boolean contExist=false;
		boolean topicExist=false;
		int total=0;
		List<Topic> topicList=new ArrayList<>();
		try {
			contExist= stringRedisDao.exists(Redis_Key_Count);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if(contExist){
			total=Integer.valueOf(stringRedisDao.getCacheString(Redis_Key_Count));
		}else{
			synchronized(syncLock){
				try {
					contExist= stringRedisDao.exists(Redis_Key_Count);
				} catch (Exception e) {
					log.error(e.getMessage());
				}
				if(contExist){
					total=Integer.valueOf(stringRedisDao.getCacheString(Redis_Key_Count));
				}else{
					total=topicDao.selectUserIdCounttopic(userId,key);
					try {
						stringRedisDao.setCacheString(Redis_Key_Count, total+"");
						stringRedisDao.setTimeout(Redis_Key_Count, ConstData.REDIS_KEY_TIMEOUT);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
				}
			}
		}		
		page.setTotalRecord(total);
		page.setPageNo(pageNow);
		//根据设计师ID查询是否当前用户以关注
		GoodsUser user =userService.selectTopicIsConcern(createUser,userId,null);
		if (user!=null) {
			page.setUserInfo(user);
		}
		try {
			topicExist= stringRedisDao.exists(Redis_Key);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		if(topicExist){
			topicList=stringRedisDao.getCacheList(Redis_Key);
		}else{
			synchronized(syncLock){
				try {
					topicExist= stringRedisDao.exists(Redis_Key);
				} catch (Exception e) {
					log.error(e.getMessage());
				}
				if(topicExist){
					topicList=stringRedisDao.getCacheList(Redis_Key);
				}else{
					if(pageNow == 0){
						pageNow=1;
					}
					/*当前用户所有话题*/
					SharedProperty sp=new SharedProperty();
			    	sp.setCreateUser(userId);
			    	sp.setPageNow(pageNow);
			    	sp.setTitle(key);
			    	List<Topic> topicListS=topicDao.pageTopicList(sp);
			    	if(topicListS != null && topicListS.size() > 0){	    		
						for(Topic topicItem : topicListS){
							if(user != null){
								topicItem.setUser(user);
							}
							//话题图片
					    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
					    	topicItem.setTopicPictures(topicPictureList);
					    	topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
					    	topicList.add(topicItem);
						}
			    	}
					try {
						stringRedisDao.setCacheList(Redis_Key, topicList);
						stringRedisDao.setTimeout(Redis_Key, ConstData.REDIS_KEY_TIMEOUT);
					} catch (Exception e) {
						log.error(e.getMessage());
					}
				}
			}
		}
				
		if(!topicList.isEmpty() && topicList.size() > 0){
    		page.setItemList(topicList);
    	}
		return page;
	}
	@Override
	public PageUtil<Topic> topicQuery(String key,long curUserId,Integer pageNow) {
		List<Topic> topicList =new ArrayList<>();
		PageUtil<Topic> page = new PageUtil<>();
		Integer totalRecord= 0;
		try {
			if(pageNow == 0){
				pageNow=1;
			}
			
			SharedProperty sp=new SharedProperty();
	    	sp.setPageNow(pageNow);
	    	sp.setCreateUser(curUserId);
	    	if(key!=null && !"".equals(key)){
	    		sp.setTitle(key);
	    	}
	    	totalRecord = topicDao.countTopicByTitle(key);
	    	
			List<Topic> topicListS = topicDao.selectTopicListByQuery(sp);
			if(topicListS != null && topicListS.size() > 0){
				for(Topic topicItem : topicListS){
					//话题图片信息
					List<TopicPicture> topicPictureList = topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
					if(!topicPictureList.isEmpty() && topicPictureList.size() > 0){
						topicItem.setTopicPictures(topicPictureList);
					}
					/*用户信息*/
					GoodsUser user= userService.selectTopicIsConcern(curUserId, topicItem.getCreateUser(), null);
					topicItem.setUser(user);
					//清除 和 替换 html代码
					topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
					
					topicList.add(topicItem);
				}
			}
			page.setPageNo(pageNow);
			page.setTotalRecord(totalRecord);
			page.setItemList(topicList);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return page;
	}
	@Override
	public PageUtil<com.zimmur.solr.model.Topic> topicQueryBySolr(String key,long curUserId,Integer pageNow) {
		List<com.zimmur.solr.model.Topic> topicList =new ArrayList<>();
		PageUtil<com.zimmur.solr.model.Topic> page = null;
		try {
			if(pageNow == 0){
				pageNow=1;
			}
			page=solrTopicService.queryTopic(key, pageNow);	
			topicList = page.getItemList();
			if(topicList != null && topicList.size() > 0){
				for(com.zimmur.solr.model.Topic topicItem : topicList){
					//话题图片信息
					List<TopicPicture> topicPictureList = topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
					if(!topicPictureList.isEmpty() && topicPictureList.size() > 0){
						topicItem.setTopicPictures(topicPictureList);
					}
					/*用户信息*/
					GoodsUser user= userService.selectTopicIsConcern(curUserId, topicItem.getCreateUser(), null);
					topicItem.setUser(user);
					//清除 和 替换 html代码
					topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
				}
			}
			page.setPageNo(pageNow);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			page=new PageUtil<>();
		}
		return page;
	}
	@Override
	public List<Topic> myCollectTopicList(long createUser, Integer pageNow) {
		List<Topic> topicList =new ArrayList<>();
		try {
			if(pageNow == 0){
				pageNow=1;
			}
			SharedProperty sp=new SharedProperty();
	    	sp.setUserId(createUser);
	    	sp.setPageNow(pageNow);
	    	TreeSet<Long> topicCollectSet  = topicCollectDao.selectByCreateUserTopicCollectSet(sp);
			if(topicCollectSet != null && topicCollectSet.size() > 0){
				//话题ID集合一次性in查询出来
				List<Topic> topicListS = selectListByTopicIds(topicCollectSet);
				for(Topic topicItem : topicListS){
					//话题图片
			    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
			    	topicItem.setTopicPictures(topicPictureList);
			    	topicItem.setIsCollect(1);
			    	//根据设计师ID查询是否当前用户以关注
			    	//int topicType=topicItem.getTopicType()==null?3:topicItem.getTopicType();
					GoodsUser user =userService.selectTopicIsConcern(createUser,topicItem.getCreateUser(),null);	
					topicItem.setUser(user);
					//清除 和 替换 html代码
					topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
					topicList.add(topicItem);
				}
			}

		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return topicList;
	}
	@Override
	public List<Topic> myInvolvementTopic(long createUser, Integer pageNow) {
		List<Topic> topicList =new ArrayList<>();
		try {
			if(pageNow == 0){
				pageNow=1;
			}
			SharedProperty sp=new SharedProperty();
	    	sp.setCreateUser(createUser);
	    	sp.setPageNow(pageNow);
	    	TreeSet<Long> topicCommentSet = topicCommentService.selectByCreateUserTopicCommentSet(sp);
			if(!topicCommentSet.isEmpty() && topicCommentSet.size() > 0){
				//话题ID集合一次性in查询出来
				List<Topic> topicListS = selectListByTopicIds(topicCommentSet);
				for(Topic topicItem : topicListS){
					//话题图片
			    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
			    	topicItem.setTopicPictures(topicPictureList);
			    	//根据设计师ID查询是否当前用户以关注
			    	//int topicType=topicItem.getTopicType()==null?3:topicItem.getTopicType();
					GoodsUser user =userService.selectTopicIsConcern(createUser,topicItem.getCreateUser(),null);	
					topicItem.setUser(user);
					//清除 和 替换 html代码
					topicItem.setContent(HtmlToTextUtil.htmlToText(topicItem.getContent()));
					topicList.add(topicItem);
				}
			}

		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return topicList;
	}
	@Override
	public List<Topic> selectListByTopicIds(TreeSet<Long> topicIds) {
		List<Topic> topicList=null;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("topicIds", topicIds);
			
			//从数据库读取
			topicList = topicDao.selectListByTopicIds(map);		
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return topicList;
	}
	@Override
	public int indexCountTopic(SharedProperty SharedProperty) {
		return topicDao.countTopicByQuery(SharedProperty);
	}
	@Override
	public PageUtil<Topic> indexTopicList(long createUser, Integer pageNow,AppModuleEnum module) {
		if(pageNow == 0){
			pageNow=1;
		}
		PageUtil<Topic> page = new PageUtil<>();
		String indexTopicList_RedisKey = redis_key+"_"+ pageNow+"_"+module.getModuleId()+"_indexTopicList";
		String indexTopicList_Count_Key = redis_key+"_"+module.getModuleId()+"_indexTopicList_count";
		List<Topic> topicList = new ArrayList<>();
		boolean countExist=false;
		boolean topicExist=false;
		//获取 最大值
		Integer totalRecord = 0;
		try {
			try {
				countExist =stringRedisDao.exists(indexTopicList_Count_Key);
			} catch (Exception e1) {
				log.error(e1.getMessage());
			}
			if(countExist){
				totalRecord = Integer.parseInt(stringRedisDao.getCacheString(indexTopicList_Count_Key));
			}else{
				synchronized (syncLock) {
					try {
						countExist =stringRedisDao.exists(indexTopicList_Count_Key);
					} catch (Exception e1) {
						log.error(e1.getMessage());
					}
					if(countExist){
						totalRecord = Integer.parseInt(stringRedisDao.getCacheString(indexTopicList_Count_Key));
					}else{
						SharedProperty sp=new SharedProperty();
				    	sp.setPageNow(pageNow);
				    	sp.setModuleId(module.getModuleId());
				    	//统计推荐话题
				    	totalRecord =topicMessageRecommandService.selectTopicMessageRecommandCount(module.getModuleId());
				    	try {
			    			stringRedisDao.del(indexTopicList_RedisKey);
			    			stringRedisDao.setCacheString(indexTopicList_Count_Key, String.valueOf(totalRecord));
			    			stringRedisDao.setTimeout(indexTopicList_Count_Key, ConstData.REDIS_KEY_TIMEOUT);
						} catch (Exception e) {
							log.error(e.getMessage());
						}
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		page.setTotalRecord(totalRecord);
		page.setPageNo(pageNow);
		
		try {
			try {
				topicExist=stringRedisDao.exists(indexTopicList_RedisKey);
			} catch (Exception e1) {
				log.error(e1.getMessage());
			}
			if(topicExist){
				//从缓存中读取
				topicList = stringRedisDao.getCacheList(indexTopicList_RedisKey);	
			}else{
				synchronized (syncLockList) {
					try {
						topicExist=stringRedisDao.exists(indexTopicList_RedisKey);
					} catch (Exception e1) {
						log.error(e1.getMessage());
					}
					if(topicExist){
						//从缓存中读取
						topicList = stringRedisDao.getCacheList(indexTopicList_RedisKey);	
					}else{
						SharedProperty sp=new SharedProperty();
				    	sp.setPageNow(pageNow);
				    	sp.setModuleId(module.getModuleId());
						TreeSet<Long> topicMessageRecommandSet  = topicMessageRecommandService.selectTopicMessageRecommandSet(sp);
						if(!topicMessageRecommandSet.isEmpty() && topicMessageRecommandSet.size() > 0){
							//话题ID集合一次性in查询出来
							List<Topic> topicLists = selectListByTopicIds(topicMessageRecommandSet);
					    	if(topicLists != null && topicLists.size() > 0){
								for(Topic topicItem : topicLists){
						    		//话题图片
							    	List<TopicPicture> topicPictureList=topicPictureDao.selectByTopicIdTopicPictureList(topicItem.getTopicId());
							    	topicItem.setTopicPictures(topicPictureList);
							    	topicList.add(topicItem);
								}
					    	}
						}
						if(!topicList.isEmpty()){
							try {
								stringRedisDao.setCacheList(indexTopicList_RedisKey, topicList);
								stringRedisDao.setTimeout(indexTopicList_RedisKey, ConstData.REDIS_KEY_TIMEOUT);
							} catch (Exception e) {
								log.error(e.getMessage());
							}
						}
					}
				}
			}
			if(topicList != null && topicList.size() > 0){
				for(Topic topicItem : topicList){
					//根据设计师ID查询是否当前用户以关注
					GoodsUser user =userService.selectTopicIsConcern(createUser, topicItem.getCreateUser(), null);
					topicItem.setUser(user);
				}
				page.setItemList(topicList);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return page;
	}
	@Override
	public int updateStopicrewardStatus(Topic topic) {
		return topicDao.updateStopicrewardStatus(topic);
	}
	
	@Transactional(isolation=Isolation.READ_COMMITTED,rollbackFor = {RuntimeException.class})
	public boolean topicReward(long topicId, long commentId) {
		Topic topic =topicDao.selectByTopicId(topicId);
        boolean bResult=false;
      //赏金不足时，不可以发布
        if(topic != null && topic.getRewardStatus()==0){
        	try{

            	long userId = topic.getCreateUser();
    	        AccountInfo curJeUserInfo= accountInfoService.selectByUserId(userId);
    	        if(topic.getReward() > curJeUserInfo.getUseJe()){
    	        	return false;
    	        }else{
    	        	TopicComment topicComment = topicCommentDao.selectByCommentId(commentId);
    	        	if(topicComment == null){
    	        		return false;
    	        	}
    	        	long toUserId = topicComment.getCreateUserId();
    	        	//消费占用余额
    	        	if(accountInfoService.updateUseJe(userId,topic.getReward(),"话题打赏")){    	        		
    	        		//更新用户金额
    	        		if(accountInfoService.updateCurJeByUserId(toUserId,topic.getReward(),"话题打赏")){
    	        			UserjeLog log = new UserjeLog();
    	        			log.setUserId(toUserId);
    	        			log.setEventDate(DateUtils.getNowUnixTime());
    	        			log.setEvent("+");
    	        			log.setJe(topic.getReward());
    	        			log.setRemark("话题打赏");
    	        			userjeLogService.insert(log);
    	        			
    	        			topicCommentService.updateCommentRewardStatus(topicId,commentId, 1);
    	        			topic.setRewardStatus(1);
    	        			updateStopicrewardStatus(topic);
    	        			bResult = true;
    	        		}
    	        	}
    	        }
        	}catch(Exception er){
        		log.error(er.getMessage());
        		Throwables.propagate(er);
        		bResult = false;
        	}
        }
		return bResult;
	}
	@Override
	public PageUtil<Topic> selectTopicByCreateUser(long createUser,Integer topicType, Integer pageNow) {
		if(pageNow == 0){
			pageNow=1;
		}
		PageUtil<Topic> page = new PageUtil<>();
		String indexTopicList_RedisKey = redis_key+"_"+ pageNow+"_"+createUser+"_"+"_selectTopicByCreateUser";
		String indexTopicList_Count_Key = redis_key+"_"+createUser+"_"+"_count_selectTopicByCreateUser";
		List<Topic> topicList = new ArrayList<>();
		boolean existTopic=false;
		boolean existCount=false;
		//获取 最大值
		Integer totalRecord = 0;
		try {
			try {
				existCount=stringRedisDao.exists(indexTopicList_Count_Key);
			} catch (Exception e1) {
				log.error(e1.getMessage());
			}
			if(existCount){
				totalRecord = Integer.parseInt(stringRedisDao.getCacheString(indexTopicList_Count_Key));
			}else{
				synchronized (syncLock) {
					try {
						existCount=stringRedisDao.exists(indexTopicList_Count_Key);
					} catch (Exception e1) {
						log.error(e1.getMessage());
					}
					if(existCount){
						totalRecord = Integer.parseInt(stringRedisDao.getCacheString(indexTopicList_Count_Key));
					}else{
						//衣匠的话题数
				    	totalRecord =topicDao.countByCreateUser(createUser,topicType);
				    	if(totalRecord > 0){
				    		page.setTotalRecord(totalRecord);
				    		page.setPageNo(pageNow);
				    		try {
				    			stringRedisDao.del(indexTopicList_RedisKey);
				    			stringRedisDao.setCacheString(indexTopicList_Count_Key, String.valueOf(totalRecord));
				    			stringRedisDao.setTimeout(indexTopicList_Count_Key, ConstData.REDIS_KEY_TIMEOUT);
							} catch (Exception e) {
								log.error(e.getMessage(),e);
							}
				    	}
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		page.setTotalRecord(totalRecord);
		page.setPageNo(pageNow);
		
		try {
			try {
				existTopic=stringRedisDao.exists(indexTopicList_RedisKey);
			} catch (Exception e1) {
				log.error(e1.getMessage());
			}
			if(existTopic){
				//从缓存中读取
				topicList = stringRedisDao.getCacheList(indexTopicList_RedisKey);
			}else{
				synchronized (syncLockList) {
					try {
						existTopic=stringRedisDao.exists(indexTopicList_RedisKey);
					} catch (Exception e1) {
						log.error(e1.getMessage());
					}
					if(existTopic){
						//从缓存中读取
						topicList = stringRedisDao.getCacheList(indexTopicList_RedisKey);
					}else{
						topicList=topicDao.selectListByCreateUser(createUser, page.getPageBeginNo(), page.getPageSize(),topicType);
						if(topicList!=null && topicList.size()>0){
							try {
								stringRedisDao.setCacheList(indexTopicList_RedisKey, topicList);
								stringRedisDao.setTimeout(indexTopicList_RedisKey, ConstData.REDIS_KEY_TIMEOUT);
							} catch (Exception e) {
								log.error(e.getMessage());
							}
						}
					}
				}
			}
			if(topicList!=null && topicList.size()>0){
				page.setItemList(topicList);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return page;
	}
  
	public void saveTopicIdToRedis(long topicId){
		boolean isExist=false;
		String topicIds;
		try {
			isExist=stringRedisDao.exists(ConstData.solr_topicIds);
			if(isExist){
				topicIds=stringRedisDao.getCacheString(ConstData.solr_topicIds);
			}else{
				topicIds="";
			}
			topicIds=topicIds+topicId+",";
			stringRedisDao.setCacheString(ConstData.solr_topicIds, topicIds);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
}  
